var hdaccounts = (function () {
    var returnid, aID = 0;
    this.ShowPage = function (pageid) {
        returnid = pageid;
        $.mobile.changePage("#page6");
    };
    function Refresh (results){
        var i, num, str = "";
        num = results.rows.length;
        if (num !== 0) {
            for(i=0; i < num; i += 1){
                str += "<li><a style='display: inline-block; padding: 14px; font-size: 14px;' accountID='" +
                    results.rows.item(i).AccountID + "' >" + results.rows.item(i).Name + ": </a>" +
                    "<span style='display: inline-block; font-size: 10px;'>" + addCommas(results.rows.item(i).Sum) +
                    " RSD</span></li>";
            }

        }
        $("#lvAccountList").html(str).listview('refresh');
    }

    this.init = function () {
        $("#lvAccountList").delegate("li", "click", function () {
            aID = parseInt($("a",this).attr("accountID"));
            $("#txtAccountName").val($("a",this).html().split(':')[0]);
            $("#btnDeleteAccount").css("display","block");
            $.mobile.changePage("#page7");
        });
        //data.getAccountList( Refresh);

        $("#btnAccountListCancel").click(function () {
            data.getAccountList( Refresh );
            $.mobile.changePage("#page" + returnid);
            
        });
        $("#btnAccountSubmit").click(function () {
            var newData;
            
            newData = {
                AccountID: aID,
                Name:$("#txtAccountName").val(), 
                Sum: 0
            }
            if(aID === 0){
                data.saveAccount(
                    function () {
                        data.getAccountList( Refresh );
                        $("#txtAccountName").val("");
                        $.mobile.changePage("#page6");
                    }
                    , newData
                );
            }else{
                data.editAccount(
                    function () {
                        data.getAccountList( Refresh );
                        $("#txtAccountName").val("");
                        $.mobile.changePage("#page6");
                    }, newData
                );
            }
        });
    
        $("#btnAccountCancel").click(function () {
            $("#txtAccountName").val("");
        });

        $("#btnAddAccount").click(function(){
            $("#txtAccountName").val("");
            aID=0;
            $("#btnDeleteAccount").css("display","none");
        });
        $("#btnDeleteAccount").click( function (){
            data.deleteAccount(aID,Refresh);
            $("#txtAccountName").val("");
            $.mobile.changePage("#page6");
        });
    };
    this.updateAccounts = function (){
        data.getAccountList( Refresh );
    };
    this.init();
    return this;
})(hdaccounts || {});